<?php

class UserController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
        $this->_helper->cache(array('index', 'register', 'login'), array('bbbbyyyyyy'));
    }

    public function indexAction()
    {
        $modelUser = new Ms_Model_User();
        $where = array('status'=>1);
        $users = $modelUser->getUsers($where);
        $this->view->users = $users;
    }

    /**
     * 注册用户
     *
     * 如果有表单提交内容，获取并将其传递给模型以创建用户
     * 表单成功提交后，跳转到用户帐号页面以查看信息
     * 没有表单提交，则显示表单
     *
     *
     */
    public function registerAction()
    {
        $formRegister = new Ms_Form_User();
        $formRegister->removeElement('avatar');
        $formRegister->removeElement('status');
        $formRegister->removeElement('profile');
        $formRegister->removeElement('role');
        $formRegister->removeElement('star');
        if ($this->getRequest()->isPost()){
            if ($formRegister->isValid($_POST)){
                $userData = $formRegister->getValues();
                
                // 实例化用户模型
                $modelUser = new Ms_Model_User();
                $validUser = $modelUser->validUser($formRegister->getValue('username'));
                if ($validUser == FALSE){
                    $newUser = $modelUser->createUser($userData);
                    if ($newUser){
                        set_time_limit(0);//不限时间。默认时间为30秒
                        $mailTransport = new Zend_Mail_Transport_Smtp('smtp.qq.com', // 你的smtp服务器
                            array( 'auth' => 'login',
                                   'username' => '418946897@qq.com', // 你的邮箱用户名
                                   'password' => 'Gl335577Yl',  //你的邮箱登录密码
                                   'ssl' => 'ssl'));
                        $mail = new Zend_Mail('utf-8');
                        $mail->setBodyHtml('<p>'.$formRegister->getValue('username').'，欢迎你注册成为我们的用户！。</p>');
                        $mail->setSubject('欢迎成为猫神网的用户');
                        $mail->setFrom('mao-shen@qq.com', 'maoshen');
                        $mail->addTo($formRegister->getValue('email'), $formRegister->getValue('username'));
                        $mail->send($mailTransport);
                        
                        $this->_forward('login');
                    }
                    else {
                        throw new Zend_Exception('添加用户出错！');
                    }
                }
                else{
                    $this->view->message = "对不起，已经存在同名用户，请换一个用户名再试一下。";
                }
            }
        }
        $this->view->formRegister = $formRegister;
    }

    /**
     * 用户页面
     *
     * 用户详细信息页面。登录用户也可在此页面修改个人信息和密码等
     *
     *
     */
    public function accountAction()
    {
        $module = $this->_request->getParam('module');
        if ($module == 'admin'){
            $this->_helper->layout->setLayout('admin');
        }
        else{
            $this->_helper->layout->setLayout('community');
        }
        
        $auth = Zend_Auth::getInstance();
        if ($auth->hasIdentity()){
            $this->view->identity = $auth->getIdentity();
        }
        
        $id = $this->_request->getParam('id');
        $modelUser = new Ms_Model_User();
        $user = $modelUser->getUser($id);
        $this->view->user = $user;
        
        // 用户的博客
        $modelBlog = new Ms_Model_Page();
        $where = array('uid'=>$id, 'type'=>'blog');
        $blogs = $modelBlog->getPages($where);
        if ($blogs){
            $paginatorBlog = new Zend_Paginator($blogs);
            $paginatorBlog->setItemCountPerPage('10');
            $page = $this->_request->getParam('page');
            $paginatorBlog->setCurrentPageNumber($page);
            $this->view->blogs = $paginatorBlog;
        }
        else{
            $this->view->blogs = null;
        }
        
        
        // 用户的论坛主题
        $modelTopic = new Ms_Model_ForumTopic();
        $topics = $modelTopic->getTopics(null,$id);
        if ($topics){
            $paginatorTopic = new Zend_Paginator($topics);
            $paginatorTopic->setItemCountPerPage('20');
            $page = $this->_request->getParam('page');
            $paginatorTopic->setCurrentPageNumber($page);
            $this->view->topics = $paginatorTopic;
        }
        else{
            $this->view->topics = null;
        }
    }

    /**
     * 用户登录
     *
     * 用户登录表单
     * 如果提交，处理表单提交数据
     * 登录成功，跳转到用户页面
     *
     *
     */
    public function loginAction()
    {
        $formLogin = new Ms_Form_User();
        $formLogin->removeElement('sex');
        $formLogin->removeElement('email');
        $formLogin->removeElement('avatar');
        $formLogin->removeElement('password2');
        $formLogin->removeElement('status');
        $formLogin->removeElement('profile');
        $formLogin->removeElement('role');
        $formLogin->removeElement('star');
        if ($this->getRequest()->isPost()){
            if ($formLogin->isValid($_POST)){
                $data = $formLogin->getValues();
                
                // 取得默认的数据库适配器
                $db = Zend_Db_Table::getDefaultAdapter();
                // 实例化一个auth适配器
                $authAdapter = new Zend_Auth_Adapter_DbTable($db, 'core_users', 'username', 'password');
                // 设置认证用户名和密码
                $authAdapter->setIdentity($data['username']);
                $authAdapter->setCredential(md5($data['password']));
                // 实现authenticate方法
                $result = $authAdapter->authenticate();
                if ($result->isValid()){
                    // 获得getInstance实例
                    $auth = Zend_Auth::getInstance();
                    // 存储用户信息
                    $storage = $auth->getStorage();
                    $storage->write($authAdapter->getResultRowObject(
                        array('id', 'username', 'role')
                    ));
                    $id = $auth->getIdentity()->id;// 获取用户id
                    // 记录登录时间
                    $modelUser = new Ms_Model_User();
                    $loginTime = $modelUser->loginTime($id);
                    
                    return $this->_redirect('/user/account/id/'.$id);
                }
                else{
                    $this->view->loginMessage = "对不起，你的用户名或密码不符。";
                }
            }
        }
        $this->view->formLogin = $formLogin;
    }

    /**
     * 用户面板
     * 
     * 获取身份
     */
    public function panelAction()
    {
        $auth = Zend_Auth::getInstance();
        if ($auth->hasIdentity()) {
            $this->view->identity = $auth->getIdentity();
        }
    }

    /**
     * 重置密码
     *
     * 将用户的密码更新为一个随机字符串
     * 将该密码发送给用户的注册邮箱
     *
     *
     */
    public function resetPasswordAction()
    {
        $formUser = new Ms_Form_User();
        $authAdapter = Zend_Auth::getInstance();
        $userInfo = $authAdapter->getIdentity();
        if ($userInfo) {
            $formUser->removeElement('username');
        }
        $formUser->removeElement('sex');
        $formUser->removeElement('email');
        $formUser->removeElement('avatar');
        $formUser->removeElement('password');
        $formUser->removeElement('password2');
        $formUser->removeElement('status');
        $formUser->removeElement('profile');
        $formUser->removeElement('role');
        $formUser->removeElement('star');
        if ($this->getRequest()->isPost()){
            if ($formUser->isValid($_POST)){
                $modelUser = new Ms_Model_User();
                $username= $formUser->getValue('username');
                $isLogin = empty($username);
                if ($isLogin) {
                    $username = $userInfo->username;
                }
                $where = array('username'=> $username);
                $user = $modelUser->getUser($where);
                if ($user){
                    $newPassword = $this->_makePassword(6);
                    $modelUser->updateUser($user->id, null, $newPassword);
                    
                    set_time_limit(0);//不限时间。默认时间为30秒
                    $mailTransport = new Zend_Mail_Transport_Smtp('smtp.qq.com',
                        array( 'auth' => 'login',
                               'username' => '418946897@qq.com',  // 邮箱用户名
                               'password' => 'Gl335577Yl',  // 邮箱密码
                               'ssl' => 'ssl'));
                    $mail = new Zend_Mail('utf-8');
                    $mail->setBodyHtml('<p>您的密码被系统重置为：'.$newPassword.'<br />建议您在下次登录后重新更改为容易记忆的新密码。</p>');
                    $mail->setSubject('您在猫神网的新密码');
                    $mail->setFrom('mao-shen@qq.com', 'maoshen');
                    $mail->addTo($user->email, $user->username);
                    $mail->send($mailTransport);
                    
//                    $this->_redirect('/user/info/conf/resetpsw_success');
                    $result = "新密码已发送到注册的邮箱【{$user->email}】！";
                    if ($isLogin) {
                        $authAdapter = Zend_Auth::getInstance();
                        $authAdapter->clearIdentity();
                        $result = '用户已退出，'.$result;
                    }
                    $this->view->result = $result;
                }
            }
        }
        $this->view->formUser = $formUser;
    }

    /**
     * 生成随机密码
     *
     * @param int $length
     *
     *
     */
    protected function _makePassword($length)
    {
        $possible = "0123456789!@#$%^&*()_+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $str = "";
        while(strlen($str) < $length){
            $str .= substr($possible, (rand() % strlen($possible)), 1);
        }
        return($str);
    }

    /**
     * 获取上传文件扩展名
     * @param String $name
     *
     */
    protected function _getExtension($fileInfo)
    {
        $fileName='';
        if($fileInfo)
        {
            foreach ($fileInfo as $value)
            {
                $fileName=$value['name'];
            }
            $exts = explode("[/.]", $fileName) ;
            $n = count($exts)-1;
            $exts = $exts[$n];
            return $exts;
        }
    }

    /**
     * 确认信息
     *
     *
     *
     */
    public function infoAction()
    {
        $conf = $this->_request->getParam('conf');
        switch ($conf){
            case 'resetpsw_success':
                echo "密码重置成功，请到您的注册邮箱中查收新密码。";
                break;
        }
    }

    /**
     * 用户信息修改
     *
     * 用户登录后可自行修改信息
     * 包括头像上传
     *
     * @throws Zend_Exception
     *
     *
     */
    public function updateAction()
    {
        $id = $this->_request->getParam('id');
        $formUser = new Ms_Form_User();
        $formUser->removeElement('username');
        $formUser->removeElement('password');
        $formUser->removeElement('password2');
        $formUser->removeElement('role');
        $formUser->removeElement('status');
        $modelUser = new Ms_Model_User();
        if ($this->getRequest()->isPost()){
            if ($formUser->isValid($_POST)){
                // 上传和获取图片信息
                $adapter = new Zend_File_Transfer_Adapter_Http();
                $path = APPLICATION_PATH.'/../public/uploads/'.date("Y-m").'/avatar/';
                $folder = new Zend_Search_Lucene_Storage_Directory_Filesystem($path); //如果文件夹不存在，则创建
                $fileInfo = $adapter->getFileInfo();//获取基本配置
                $extName = $this->_getExtension($fileInfo);//获取扩展名
                $filename = time().'.'.$extName;//重命名
                $adapter->addFilter('Rename', array('target' => $filename, 'overwrite' => true));//执行重命名
                $adapter->setDestination($path); //设定保存路径
                $adapter->addValidator('Size',FALSE, 128000 ); // 上传文件大小
                $adapter->addValidator('Extension', FALSE, array('jpg', 'gif', 'png', 'jpeg')); //扩展名验证
                
                // 获取其它表单数据
                $data = array();
                $data['sex'] = $formUser->getValue('sex');
                $data['email'] = $formUser->getValue('email');
                $data['profile'] = $formUser->getValue('profile');
                
                
                if ($adapter->receive()) { //如执行上传
                    $data['avatar'] = $filename;
                    $updateUser = $modelUser->updateUser( $id, $data);

                }
                else{
                    if($formUser->getValue('avatar')){
                        throw new Zend_Exception('图片太大或格式不对，未能成功上传');
                        exit;
                    }
                    else{
                        $updateUser = $modelUser->updateUser($id, $data);
                    }
                    
                }
                
                if (updateUser){
                    $this->_redirect('user/account/id/'.$id.'/'.$updateUser);
                }
                else{
                    throw new Zend_Exception('更新用户信息出错！');
                }
            }
            
        }
        $user = $modelUser->find($id)->current();
        $formUser->populate($user->toArray());
        $this->view->user = $user;
        $this->view->formUser = $formUser;
    }

    /**
     * 更改密码
     *
     */
    public function changePasswordAction()
    {
        $id = $this->_request->getParam('id');
        $formUser = new Ms_Form_User();
        $formUser->removeElement('username');
        $formUser->removeElement('sex');
        $formUser->removeElement('email');
        $formUser->removeElement('avatar');
        $formUser->removeElement('profile');
        $formUser->removeElement('role');
        $formUser->removeElement('star');
        $formUser->removeElement('status');
        if ($this->getRequest()->isPost()){
            if ($formUser->isValid($_POST)){
                $modelUser = new Ms_Model_User();
                $newpsw = $modelUser->changPassword($id, $formUser->getValue('password'));
                
                return $this->_forward('account');
            }
        }
        $this->view->formUser = $formUser;
    }

    /**
     * 用户注销
     * 
     */
    public function logoutAction()
    {
        // 注销用户
       $authAdapter = Zend_Auth::getInstance();
       $authAdapter->clearIdentity();
        $this->_redirect('/');
    }


}



















